<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { chessGameService } from '../services/ChessGameService';
import { userService } from '../services/UserService';
import Chessboard from './Chessboard.vue';
import { mqttService } from '../services/MQTTService';
import CustomConfirm from './CustomConfirm.vue';

const confirmRef = ref(null);

// 计算游戏状态文本
const gameStatusText = computed(() => {
  switch (chessGameService.status.value) {
    case 'idle':
      return '空闲中';
    case 'matching':
      return '匹配中...';
    case 'playing':
      return '对局中';
    case 'game_over':
      return '游戏结束';
    default:
      return '未知状态';
  }
});

// 计算当前玩家阵营文本
const campText = computed(() => {
  if (chessGameService.status.value !== 'playing' && chessGameService.status.value !== 'game_over') {
    return '';
  }
  return chessGameService.myCamp.value === 'red' ? '红方' : '黑方';
});

// 计算对手信息
const opponentInfo = computed(() => {
  if (!chessGameService.room.players || chessGameService.room.players.length < 2) {
    return { userId: '', username: '等待对手' };
  }

  const myUserId = userService.userId.value;
  const opponent = chessGameService.room.players.find(
    player => player.userId !== myUserId
  );

  return opponent ? { userId: opponent.userId, username: opponent.username } : { userId: '', username: '未知对手' };
});

// 计算游戏结果文本
const gameResultText = computed(() => {
  if (chessGameService.status.value !== 'game_over') {
    return '';
  }

  if (chessGameService.room.winner === userService.userId.value) {
    return '你赢了！';
  } else if (chessGameService.room.winner === '') {
    return '平局';
  } else {
    return '你输了';
  }
});

// 开始匹配
const startMatching = () => {
  chessGameService.startMatching();
};

// 取消匹配
const cancelMatching = () => {
  chessGameService.cancelMatching();
};

// 认输
const surrender = async () => {
  const shouldSurrender = await confirmRef.value.show({
    title: '确认认输',
    message: '确定要认输吗？'
  });

  if (shouldSurrender && chessGameService.room.players?.length >= 2) {
    chessGameService.handleGameOver(userService.userId.value === chessGameService.room.players[0].userId
      ? chessGameService.room.players[1].userId
      : chessGameService.room.players[0].userId);
  }
};

// 返回大厅
const backToLobby = () => {
  chessGameService.startNewGame();
};

// 控制“开始匹配”按钮是否可用
const canStartMatching = ref(false);

// 监听 MQTT 连接状态，连接成功后 1 秒允许点击
onMounted(() => {
  if (mqttService.connectionStatus.value === '已连接') {
    setTimeout(() => { canStartMatching.value = true; }, 1000);
  }
});
watch(() => mqttService.connectionStatus.value, (val) => {
  if (val === '已连接') {
    setTimeout(() => { canStartMatching.value = true; }, 1000);
  } else {
    canStartMatching.value = false;
  }
});
</script>

<template>
  <div class="chess-panel">
    <div class="game-header">
      <div class="game-title">中国象棋</div>
      <div class="game-status" :class="chessGameService.status.value">
        {{ gameStatusText }}
        <span v-if="campText" class="camp-text">({{ campText }})</span>
      </div>
    </div>

    <div class="connection-info">
      <div class="mqtt-status">
        MQTT状态: {{ mqttService.connectionStatus.value }}
      </div>
      <div class="user-info">
        用户ID: {{ userService.userId.value.substring(0, 8) }}...
      </div>
    </div>

    <div class="game-content">
      <div class="player-info-section">
        <div class="player-info my-info">
          <div class="player-details">
            <div class="player-name">{{ userService.username.value }}</div>
            <div class="player-id">ID: {{ userService.userId.value }}</div>
          </div>
        </div>

        <div class="vs-indicator">VS</div>

        <div class="player-info opponent-info">
          <div class="player-details">
            <div class="player-name">{{ opponentInfo.username }}</div>
            <div class="player-id" v-if="opponentInfo.userId">ID: {{ opponentInfo.userId }}</div>
          </div>
        </div>
      </div>

      <Chessboard v-if="chessGameService.status.value === 'playing' || chessGameService.status.value === 'game_over'" />

      <div v-if="chessGameService.status.value === 'game_over'" class="game-result">
        {{ gameResultText }}
      </div>

  <CustomConfirm ref="confirmRef" />
  <div class="action-buttons">
    <button
      v-if="chessGameService.status.value === 'idle'"
      class="primary-button"
      @click="startMatching"
      :disabled="!canStartMatching"
    >
      开始匹配
    </button>

        <button
          v-if="chessGameService.status.value === 'matching'"
          class="secondary-button"
          @click="cancelMatching"
        >
          取消匹配
        </button>

        <button
          v-if="chessGameService.status.value === 'playing'"
          class="danger-button"
          @click="surrender"
        >
          认输
        </button>

        <button 
          v-if="chessGameService.status.value === 'game_over'" 
          class="primary-button"
          @click="backToLobby"
        >
          返回大厅
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chess-panel {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.game-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.game-status {
  font-size: 16px;
  padding: 5px 10px;
  border-radius: 4px;
  background-color: #eaeaea;
}

.game-status.playing {
  background-color: #e6f7ff;
  color: #1890ff;
}

.game-status.matching {
  background-color: #fff7e6;
  color: #fa8c16;
}

.game-status.game_over {
  background-color: #f6ffed;
  color: #52c41a;
}

.camp-text {
  margin-left: 5px;
  font-weight: bold;
}

.game-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.player-info-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 20px;
}

.player-info {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  width: 45%;
  justify-content: center;
}

.player-details {
  text-align: center;
}

.player-name {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 5px;
}

.player-id {
  font-size: 12px;
  color: #999;
}

.vs-indicator {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.game-result {
  margin: 20px 0;
  font-size: 24px;
  font-weight: bold;
  color: #ff4d4f;
  text-align: center;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  margin: 0 10px;
}

.primary-button {
  background-color: #1890ff;
  color: white;
}

.primary-button:hover {
  background-color: #40a9ff;
}

.secondary-button {
  background-color: #f0f0f0;
  color: #333;
}

.secondary-button:hover {
  background-color: #d9d9d9;
}

.danger-button {
  background-color: #ff4d4f;
  color: white;
}

.danger-button:hover {
  background-color: #ff7875;
}

.connection-info {
  display: flex;
  justify-content: space-between;
  padding: 5px 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 12px;
  color: #666;
}

.mqtt-status {
  font-weight: bold;
}

.user-info {
  font-style: italic;
}
</style>